import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', {
  state: () => ({
    appTheme: 'light', // 应用主题
    codeTheme: 'github' // 代码块主题
  }),
  
  getters: {
    themeName: (state) => {
      const names = { light: '浅色', dark: '深色' }
      return names[state.appTheme] || '默认'
    },
    primaryColor: (state) => {
      const colors = { light: '#42b983', dark: '#2c3e50' }
      return colors[state.appTheme] || '#42b983'
    },
    // 根据应用主题自动选择合适的代码块主题
    autoCodeTheme: (state) => {
      const themeMap = { dark: 'dracula', light: 'github' }
      return themeMap[state.appTheme] || 'github'
    }
  },
  
  actions: {
    setAppTheme(theme) {
      this.appTheme = theme
      // 自动关联代码块主题
      this.codeTheme = this.autoCodeTheme
      this.saveTheme()
      this.applyTheme()
      
      // 触发代码块主题更新事件，使所有代码块跟随全局主题变化
      window.dispatchEvent(new CustomEvent('code-theme-changed', { detail: theme }))
    },
    
    setCodeTheme(theme) {
      this.codeTheme = theme
      localStorage.setItem('codeTheme', theme)
      // 触发代码块主题更新事件
      window.dispatchEvent(new CustomEvent('code-theme-changed', { detail: theme }))
    },
    
    // 保存主题到localStorage
    saveTheme() {
      localStorage.setItem('theme', this.appTheme)
    },
    
    // 应用主题到DOM
    applyTheme() {
      document.documentElement.setAttribute('data-theme', this.appTheme)
    },
    
    // 初始化主题
    initTheme() {
      // 从localStorage读取保存的主题
      const savedTheme = localStorage.getItem('theme')
      if (savedTheme && ['light', 'dark'].includes(savedTheme)) {
        this.appTheme = savedTheme
      } else {
        // 默认使用浅色主题
        this.appTheme = 'light'
      }
      
      // 读取保存的代码块主题
      const savedCodeTheme = localStorage.getItem('codeTheme')
      if (savedCodeTheme) {
        this.codeTheme = savedCodeTheme
      } else {
        this.codeTheme = this.autoCodeTheme
      }
      
      this.applyTheme()
    }
  }
})